package com.mobapping;


import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.mobapping.IDataAdapter.ElementInfo;
import com.mobapping.IDataAdapter.IArrayListDataListener;

public class Harita extends MapActivity {
	/** Called when the activity is first created. */

	private final int GPS_AKTIF_HALE_GETIRILMELI=0;
	private static final String CITY_LATITUDE = "City_latitude";
	private static final String CITY_LONGITUDE = "City_longitude";
	private LocationManager konumYoneticisi;
	private LocationListener konumDinleyicisi;
	private MapView haritaGorunumu;
	private IDataAdapter  webAdapter;
	private static final String ACTION_START_MAP = "com.listview.startmap";
	private static final String ACTION_SHOW_PHARMACY_ONMAP ="com.listview.showPharmacyonMap";
	private static final String PHARMACY_NAME = "com.listview.PharmacyonName";
	private static final String PHARMACY_ADDRESS = "com.listview.PharmacyonAdress";
	private static final String PHARMACY_PHONE = "com.listview.PharmacyonPhone";
	Drawable redmarker;
	Drawable greenmarker;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		greenmarker = this.getResources().getDrawable(R.drawable.greenmarkerr);
		redmarker = this.getResources().getDrawable(R.drawable.marker123);
		String action = getIntent().getAction(); 
		initialize_konumdinleyicisi();

		super.onCreate(savedInstanceState);
		setContentView(R.layout.harita);
		haritaGorunumu = (MapView) findViewById(R.id.mapview);
		haritaGorunumu.setBuiltInZoomControls(true);
		GeoPoint nokta = new GeoPoint((int)(38 * 1e6), (int) (36 * 1e6));
		haritaGorunumu.getController().setCenter(nokta);
		konumYoneticisi= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		webAdapter = new WebAdapter();

		if(action.equals(ACTION_START_MAP) == true){

			Intent i = getIntent();
			final PharmacyItemizedOverlay itemizedoverlay_konumum = new PharmacyItemizedOverlay(greenmarker,haritaGorunumu.getContext());
			final PharmacyItemizedOverlay itemizedoverlay_eczaneler = new PharmacyItemizedOverlay(redmarker,haritaGorunumu.getContext());
			double city_latitude=i.getDoubleExtra(CITY_LATITUDE, 0);	
			double city_longitude=i.getDoubleExtra(CITY_LONGITUDE, 0);	

			final GeoPoint city_center= new GeoPoint((int)(city_latitude* 1e6) , (int)(city_longitude* 1e6));
			//OverlayItem overlayitem = new OverlayItem(Ankaramerkeznokta, "Konumum", "");
			PharmacyOverlayItem overlayitem = new PharmacyOverlayItem(city_center, "Konumum","Alooo", "Aloooo" );

			//itemizedoverlay_konumum.addOverlay(overlayitem);

			webAdapter.search((double)city_latitude,(double)city_longitude, 250, new IArrayListDataListener() { 

				public void dataArrived(ArrayList<Object> data) {
					List <Overlay> mapOverLays= haritaGorunumu.getOverlays();
					mapOverLays.clear();
					//mapOverLays.add(itemizedoverlay_konumum);
					haritaGorunumu.getController().setCenter(city_center);
					haritaGorunumu.getController().setZoom(13);
					if (data != null) {
						int size = data.size();
						if (size > 0) {
							final GeoPoint pharmacylocations[]= new GeoPoint[size];
							final ElementInfo[] pharmacies = new ElementInfo[size];
							for (int i = 0; i < size; i++) {
								pharmacies[i]= (ElementInfo)data.get(i); 
								pharmacylocations[i]=new GeoPoint((int)(pharmacies[i].lattitude* 1e6),(int)(pharmacies[i].longitude* 1e6));
								PharmacyOverlayItem overlayitem = new PharmacyOverlayItem(pharmacylocations[i], pharmacies[i].name,  pharmacies[i].address, pharmacies[i].phoneNumber );
								itemizedoverlay_eczaneler.addOverlay(overlayitem);
							}
							mapOverLays.add(itemizedoverlay_eczaneler);
						}
					}
				}
			});
			if(konumYoneticisi.isProviderEnabled(LocationManager.GPS_PROVIDER)==true)
			{
				Thread locationUpdates = new Thread(){
					public void run(){
						Looper.prepare();
						Criteria criteria = new Criteria();
						criteria.setAccuracy(Criteria.ACCURACY_FINE);

						String provider = konumYoneticisi.getBestProvider(criteria, true);

						konumYoneticisi.requestLocationUpdates(provider, 0, 1.0f, konumDinleyicisi);
						konumYoneticisi.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, konumDinleyicisi);
						Looper.loop();							
					}
				};
				locationUpdates.start();
			}
			else {
				Toast.makeText(getApplicationContext(), getString(R.string.gps_uyari), Toast.LENGTH_LONG).show();
			}

		}
		else if(action.equals(ACTION_SHOW_PHARMACY_ONMAP) == true){
			Intent i = getIntent();

			final PharmacyItemizedOverlay itemizedoverlay_eczane = new PharmacyItemizedOverlay(redmarker,haritaGorunumu.getContext());
			double city_latitude=i.getDoubleExtra(CITY_LATITUDE, 0);	
			double city_longitude=i.getDoubleExtra(CITY_LONGITUDE, 0);
			String pharmacy_name= i.getStringExtra(PHARMACY_NAME) ;	
			String pharmacy_adress= i.getStringExtra(PHARMACY_ADDRESS) ;
			String pharmacy_phone= i.getStringExtra(PHARMACY_PHONE) ;
			final GeoPoint pharmacycoord= new GeoPoint((int)(city_latitude* 1e6) , (int)(city_longitude* 1e6));
			PharmacyOverlayItem overlayitem = new PharmacyOverlayItem(pharmacycoord, pharmacy_name,pharmacy_adress, pharmacy_phone );
			itemizedoverlay_eczane.addOverlay(overlayitem);
			List <Overlay> mapOverLays= haritaGorunumu.getOverlays();
			mapOverLays.clear();
			mapOverLays.add(itemizedoverlay_eczane);
			haritaGorunumu.getController().setCenter(pharmacycoord);
			haritaGorunumu.getController().setZoom(15);

		}
	}


	



	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		MenuInflater inflater = getMenuInflater();

		inflater.inflate(R.menu.harita_menu, menu);
		return true;

	}

	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case R.id.konumumu_haritada_goster:
			konumYoneticisi= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			if(konumYoneticisi.isProviderEnabled(LocationManager.GPS_PROVIDER)==true)
			{
				Thread locationUpdates = new Thread(){
					public void run(){
						Looper.prepare();
						konumYoneticisi.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, konumDinleyicisi);
						Looper.loop();							
					}
				};
				locationUpdates.start();
			}
			else {
				showDialog(GPS_AKTIF_HALE_GETIRILMELI);
			}
			break;

		}
		return super.onOptionsItemSelected(item);
	}


	@Override
	protected Dialog onCreateDialog(int id){
		switch(id)
		{
		case GPS_AKTIF_HALE_GETIRILMELI:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(R.string.gps_aktif_hale_getiriniz).setNeutralButton(R.string.tamam, new OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which ){
					dialog.cancel();
				}
			});
			return builder.create();
		}
		return super.onCreateDialog(id);

	}


	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}


	private void initialize_konumdinleyicisi(){
		konumDinleyicisi = new LocationListener() {
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras){

			}

			@Override
			public void onProviderEnabled(String provider){

			}

			@Override
			public void onProviderDisabled(String provider){


			}
			@Override
			public void onLocationChanged(Location location){
				final PharmacyItemizedOverlay itemizedoverlay_konumum = new PharmacyItemizedOverlay(greenmarker,haritaGorunumu.getContext());
				final PharmacyItemizedOverlay itemizedoverlay_eczaneler = new PharmacyItemizedOverlay(redmarker,haritaGorunumu.getContext());
				konumYoneticisi.removeUpdates(konumDinleyicisi);
				if(location != null)
				{
					final GeoPoint nokta= new GeoPoint((int)(location.getLatitude()* 1e6) , (int)(location.getLongitude()* 1e6));
					//    			OverlayItem overlayitem = new OverlayItem(nokta, "Konumum", "");
					PharmacyOverlayItem overlayitem = new PharmacyOverlayItem(nokta, "Konumum","Alooo", "Aloooo" );

					itemizedoverlay_konumum.addOverlay(overlayitem);

					webAdapter.search((double)location.getLatitude(),(double)location.getLongitude(), 250, new IArrayListDataListener() { 

						public void dataArrived(ArrayList<Object> data) {
							List <Overlay> mapOverLays= haritaGorunumu.getOverlays();
							mapOverLays.clear();
							mapOverLays.add(itemizedoverlay_konumum);
							haritaGorunumu.getController().setCenter(nokta);
							haritaGorunumu.getController().setZoom(13);
							if (data != null) {
								int size = data.size();
								if (size > 0) {
									final GeoPoint pharmacylocations[]= new GeoPoint[size];
									final ElementInfo[] pharmacies = new ElementInfo[size];
									for (int i = 0; i < size; i++) {
										pharmacies[i]= (ElementInfo)data.get(i); 
										pharmacylocations[i]=new GeoPoint((int)(pharmacies[i].lattitude* 1e6),(int)(pharmacies[i].longitude* 1e6));
										PharmacyOverlayItem overlayitem = new PharmacyOverlayItem(pharmacylocations[i], pharmacies[i].name,  pharmacies[i].address, pharmacies[i].phoneNumber );
										itemizedoverlay_eczaneler.addOverlay(overlayitem);
									}
									mapOverLays.add(itemizedoverlay_eczaneler);
								}
							}							
						}
					});




				}
				else{
					Toast.makeText(getApplicationContext(), R.string.gps_konum_bilgisi_hesaplanamadi,Toast.LENGTH_LONG).show();

				}

			}
		};


	}


}